<template>
  <div class="menu-wrapper">
    <category-dialog ref="supplierCategoryDialog" request="supplierCategory" @confirm="dialogConfirm"/>
    <el-form ref="supplierForm" :model="form" :rules="rules" label-width="120px" >
      <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px" v-if="!isDialog">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>

          <el-form-item label="供应商名称" prop="name">
              <el-input v-model="form.name" style="width: 265px"/>
          </el-form-item>
      <div style="display: flex">
        <el-form-item label="所属分类" style="width:270px">
          <el-input v-model="supplierCategoryName" suffix-icon="el-icon-arrow-down" @focus="dialogShow"/>
        </el-form-item>
        <el-form-item label="开票类型" style="width:220px">
          <el-select  v-model="form.taxType" placeholder="请选择类型">
            <el-option label="不开票" value="0"/>
            <el-option label="增票" value="1"/>
            <el-option label="普票" value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="税率(%)" style="width:180px">
          <el-input v-model="form.tax"/>
        </el-form-item>
      </div>
      <div style="display: flex">
        <el-form-item label="登录账号" style="width:270px">
<!--          <el-input v-model="form.username"  />-->
          <el-input v-model="form.username"/>
        </el-form-item>
        <el-form-item label="登录密码" style="width:270px">
<!--          <el-input v-model="form.password"  show-password/>-->
          <el-input v-model="form.password"/>
        </el-form-item>
      </div>

      <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px"  v-if="!isDialog">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">收货地址</span>
      </div>
      <div style="display: flex">
        <el-form-item label="收货人" prop="consignee" style="width:270px">
            <el-input v-model="form.consignee"  />
        </el-form-item>

          <el-form-item label="收货人电话" prop="mobile" style="width:270px">
            <el-input v-model="form.mobile"/>
          </el-form-item>
      </div>
      <div style="display: flex">
        <el-form-item label="所在地" prop="areaId" style="width: 550px">
            <Distpicker @selected="onSelected" :province="district.province" :city="district.city"
                        :area="district.area"></Distpicker>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="详细地址" prop="address" style="width: 550px;">
          <el-input v-model="form.address" />
        </el-form-item>
      </div>
      <el-form-item label="联系电话" style="width:270px">
        <el-input v-model="form.phone" @blur="phoneNumber"/>
      </el-form-item>
      <el-form-item label="邮箱" style="width:270px">
        <el-input v-model="form.email" @blur="sendEmail"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="clicked" @click="saveSupplier('supplierForm'),checkUser()" >
          完 成
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped>
  /deep/.el-form-item__content{
    margin-left: 40px;
  }
  .menu-wrapper {
    margin: 15px;
  }
</style>
<script>
  import {EventBus} from '@/api/eventBus'
  import utils from '../../utils/utils.js'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import {save} from '@/api/supplier'
  import {checkUserExists} from '@/api/sysUser'
  import md5 from 'js-md5';
  import CategoryDialog from '@/components/CategoryDialog'
  export default {
    name: 'supplier-add',
    filters: {},
    components: {
      Distpicker, CategoryDialog
    },
    props:{
      isDialog:false
    },
    data() {
      // var validatePass = (rule, value, callback) => {
      //   if (value === '') {
      //     callback(new Error('请输入账号'));
      //   } else if (this.isExists === true){
      //       callback(new Error('账号已存在'))
      //   }else {
      //     callback();
      //   }
      // };
      return {
        clicked: false, // 按钮防双击
        district: {province: 440000, city: '广州市', area: '海珠区'},
        isExists:false,
        tips:'',
        addForm:{
          consignee:'',
          username:'',
          name: '',
          mobile: '',
          phone: '',
          email: '',
          areaId: 440000,
          areaName: '广东省广州市海珠区',
          address: '',
          supplierCategoryId: '',
          tax:'',
          taxType:'0'
        },
        form: {
          consignee:'',
          password:'',
          username:'',
          name: '',
          mobile: '',
          phone: '',
          email: '',
          areaId: 440000,
          areaName: '广东省广州市海珠区',
          address: '',
          supplierCategoryId: '',
          tax:'',
          taxType:'0'
        },
        supplierCategoryName: '',
        rules: {
          // username:[ { validator: validatePass, trigger: 'blur' }],
          name: [
            {required: true, message: '请输入商户名称', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
          ],
          areaId: [
            {required: true, message: '请输入选择所在地', trigger: 'blur'}
          ],
          mobile: [
            {required: true, message: '请输入联系电话', trigger: 'blur'}
          ],
          address: [
            {required: true, message: '请输入详细地址', trigger: 'blur'}
          ],
        }
      }
    },
    created() {

    },
    methods: {
      onSelected(val) {
        if (!utils.isNull(val.area) && !utils.isNull(val.area.code)) {
          this.form.areaId = val.area.code;
          this.form.areaName = val.area.value;
        }
      },
      dialogShow() {
        console.log('点击了')
        this.$refs.supplierCategoryDialog.show()
      },
      dialogConfirm(val) {

        console.log(val)
        this.supplierCategoryName = val.name;
        this.form.supplierCategoryId = val.id
      },
      checkUser(){
        var _this = this
        if (!utils.isNull(this.form.username)){
          let params=new URLSearchParams()
          params.append('username',this.form.username)
          checkUserExists(params).then(res=>{
            if (res.type=='success'){
              if (!utils.isNull(_this.form.password)) {
                _this.form.password=md5(_this.form.password)
              }
              this.isExists=false
            }
          }).catch(error=>{
            this.isExists=true
          })
        }

      },
      saveSupplier(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            _this.clicked = true;
            console.log(_this.form.password)
            let params=new URLSearchParams()
            params.append('password', _this.form.password)
              this.addForm.consignee=this.form.consignee,
              this.addForm.username=this.form.username,
              this.addForm.name=this.form.name,
              this.addForm.mobile=this.form.mobile,
              this.addForm.phone=this.form.phone,
              this.addForm.email=this.form.email,
              this.addForm.areaId=this.form.areaId,
              this.addForm.areaName=this.form.areaName,
              this.addForm.address=this.form.address,
              this.addForm.supplierCategoryId=this.form.supplierCategoryId,
              this.addForm.tax=this.form.tax,
              this.addForm.taxType= this.form. taxType

            save(this.addForm ,params).then(response => {
              console.log(response)
              _this.clicked = false
              if (response.type == 'success') {
                if(!_this.isDialog){
                  EventBus.$emit('supplier-add', response.data)
                  _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                    _this.$router.push({
                      path: '/supplier/list'
                    })
                  })// 关闭当前tab回到列表
                }else {
                  _this.$emit('confirm',response.data)
                }
              } else {
                _this.$message({
                  message: response.content,
                  offset: 120,
                  center: true
                })
              }
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      sendEmail: function() {
        var regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (this.form.email != '' && !regEmail.test(this.form.email)) {
          this.$message({
            message: '邮箱格式不正确',
            type: 'error'
          })
          this.form.email = ''
        }
      },
      phoneNumber() {
        if (this.form.phone && (!(/^[1][34578]\d{9}$/).test(this.form.phone) || !(/^[1-9]\d*$/).test(this.form.phone) || this.form.phone.length !== 11)) {
          this.$message({
            message: '手机格式不正确',
            type: 'error'
          })
          this.form.phone = ''
        }
      },
    }
  }
</script>
